package modes

import (
	"fmt"
	"time"
)

type AgreeType struct {
	Id 			int64 	`json:"agrt_id" xorm:"id"`				// id
	PId			int64	`json:"agrt_pid" xorm:"pid"`			//项目id
	Term 		string	`json:"agrt_term" xorm:"term"`			//生效终端  0 未添加 1 app 2 pc
	At  		int64	`json:"agrt_at" xorm:"at"`				//生效时间
	Uname		string	`json:"agrt_dept_name" xorm:"dept_name"`		//操作坐席用户
	Start		int64	`json:"agrt_start" xorm:"start"`		//0 启用 1禁用
}

func (this *AgreeType) TableName() string {
	return  "agree_type"
}

func ( this *AgreeType )Save()( int64, error ){
	this.At = time.Now().Unix()
	this.Start = 0
	return Db(1).Insert(this)
}

func ( this *AgreeType)Get()( bool, error){
	return Db(1).Get(this)
}

func ( this *AgreeType)GetPIdTime()( bool, error){
	var val AgreeType
	where := fmt.Sprintf("pid = %d and find_in_set(%s,term) and start = 0",this.PId,this.Term)
	return Db(1).Where(where).Get(&val)
}

func (this  *AgreeType)delete( where string)(int64, error){
	return Db(1).Where(where).Delete(this)
}
func (this * AgreeType)Del()(int64, error){
	where := fmt.Sprintf("id =%d",this.Id)
	return this.delete(where)
}
func ( this *AgreeType )Count( where string )( int64, error ){
	var val LiveClass
	return  Db(1).Where(where).Count(&val)
}
func (this  *AgreeType)update( where string, field string )(int64, error){
	return Db(1).Where(where).Cols(field).Update(this)
}

func ( this *AgreeType)IdSet(field string)(int64, error)  {
	where := fmt.Sprintf("id = %d", this.Id)
	return this.update(where,field)
}

func ( this *AgreeType )where( fage, count, page int, where, field string )( []AgreeType,error ){
	list := make( []AgreeType, 0 )
	var err error
	if field == "" {
		field = "id"
	}
	if 0 == fage { // 从小到大排序
		err = Db(1).Where( where ).
			Asc( field ).
			Limit( count, page * count ).
			Find( &list )
	}else {	// 从大到小排序
		err = Db(1).Where( where ).
			Desc( field ).
			Limit( count, page * count ).
			Find( &list )
	}
	return list, err
}

type AgrePro struct {
	AgreeType    `json:"ag" xorm:"extends"`
	Project      `json:"pro" xorm:"extends"`
}
func ( this *AgrePro )Lookups(  val *Pager  ) error {
	list := make( []AgrePro, 0 )
	val.TName = "agree_type"
	val.Page --
	var field, sort string
	switch val.Coll {
	case 0: field = fmt.Sprintf("%s.id",	val.TName ) // id
	case 1: field = fmt.Sprintf("%s.pid",val.TName ) // pid
	case 2: field = fmt.Sprintf("%s.at",	val.TName ) // at
	default :field = fmt.Sprintf("%s.id",val.TName ) // id
	}
	if 1 == val.Rules {
		sort = fmt.Sprintf( "%s asc", field )
	}else{
		sort = fmt.Sprintf( "%s desc", field )
	}
	val.Total,_ = Db( 1).Table(  val.TName ).Where( val.ToWhere() ).Count( this )
	err := Db(1).Table( val.TName ).
		Join("INNER ","project",fmt.Sprintf("%s.pid =project.id",val.TName)).
		Where( val.ToWhere() ).
		OrderBy( sort ).
		Limit( val.Count, val.Page * val.Count ).
		Find( &list )
	if err == nil {
		val.List = list

	}
	return  err
}